<template>
  <div class="order-confirm" style="height:85vh" v-cloak>
    <van-cell-group>
      <van-cell center >
        <div class="top-box">
          <div class="btn_switch">
            <div class="btn-left" :class="index === 1 ? 'active' : ''" @click="Toggle(1)">自提</div>
            <div class="btn-right" :class="index === 2 ? 'active' : ''" @click="Toggle(2)">外卖</div>
          </div>
          <div class="TimeOfArrival">
            <div>{{index == 1 ? '立即取餐' : '送餐时间'}}</div>
            <div>约{{calcTimer}}可{{index == 1 ? '取餐' : '送达'}}</div>
          </div>
        </div>
      </van-cell>
    </van-cell-group>
    <van-cell-group v-if="index === 1">
      <van-cell>
        <div class="address">
          <van-cell center :title="'取餐地址： ' + PickedUpAddress.name" >
            <template #label>
              <div>{{PickedUpAddress.area}}</div>
              <div>{{PickedUpAddress.detail}}</div>
              <div>距离您：{{PickedUpAddress.distance}}m</div>
            </template>
          </van-cell>
        </div>
      </van-cell>
    </van-cell-group>
    <van-cell-group v-else>
      <van-cell v-if="AllAddress.length > 0">
        <div class="address" v-for="Addres in Address" :key="Addres.id">
          <van-cell center :title="'送货地址： ' + Addres.area + Addres.detail" @click="changeAddressType">
            <template #label>
              <div>{{Addres.name}} {{Addres.sex ? '先生' : '女士'}} {{Addres.phone}}</div>
              <div>{{Addres.is_default ? '是默认地址' : '非默认地址'}}</div>
              <div>邮编：{{Addres.ZIP_code}}</div>
            </template>
          </van-cell>
        </div>
      </van-cell>
      <van-cell v-else>
        <van-button type="primary" block @click="gotoAddArress">添加默认地址</van-button>
      </van-cell>
    </van-cell-group>

    <van-popup
    v-model="showAddress"
    closeable
    position="bottom"
    :style="{ height: '30%' }"
    round
    >
    <van-address-list
        v-model="chosenAddressId"
        :list="AllAddress"
        default-tag-text="默认"
        @select="ChangeAddressIndex"
      />
    </van-popup>

    <van-cell-group>
      <van-cell title="订单信息" />
      <van-cell v-cloak v-for="item in items" :key="item.id">
          <van-card
            :thumb="'http://img.zuiyu1818.cn' + item.shop_imgUrl"
          >
          <template #title >
            <div>{{item.shop_name}}</div>
          </template>
          <template #desc>
            <span>{{item.cup | FixCup}}{{item.sweetness | FixSweetness}}{{item.temperature | FixTemperature}}</span>
            <span style="float:right">￥{{item.shop_price}}</span>
            <div>x {{item.amount}}</div>
          </template>
          </van-card>
      </van-cell>

      <van-cell title="" style="float:right">
        <template #extra>
          合计:￥{{calcMoney}}
        </template>
      </van-cell>
      <!-- v-if="Coupons.length > 0" -->
      <van-cell   v-cloak is-link title="优惠券" @click="changeCoponType" style="color:red;" :value="coponId == null ? Coupons.length + '个可用' : Coupons[Coponindex].coupon_name + ' - ' + CoponPrice"/>
        <van-action-sheet v-model="show" title="优惠券">
          <div class="content">
            <div class="evey" v-for="(Copon, CoponIndex) in Coupons" :key="Copon.id" @click="CoponType(Copon.id,CoponIndex)" >
              <!-- active1 -->
              <div class="qianbao" :class="Copon.id === coponId ? 'active1' : ''">
                <div class="zuo">￥{{Copon.sale_num}}</div>
                <div class="zhong">
                  <div class="shang"></div>
                  <div class="xia"></div>
                </div>
                <div class="you">{{Copon.coupon_name}}<van-icon name="question-o"/></div>
              </div>
            </div>
          </div>
        </van-action-sheet>

      <van-cell is-link title="支付方式" @click="shows = true" :value="payId === 0 ? '余额' : payName"/>
      <van-action-sheet
        v-model="shows"
        :actions="actionss"
        cancel-text="取消"
        description="支付方式选择"
        close-on-click-action
        @select="PayType"
      />
    </van-cell-group>
    <van-submit-bar :price="calcTotalMoney" @submit="SubmitOrder" button-text="提交订单" >
  </van-submit-bar>
  </div>
</template>

<script>
import Vue from 'vue'
import { Cell, CellGroup, Card, Image as VanImage, Switch, ActionSheet, Icon, SubmitBar, Popup, AddressList, Notify, Toast, Button, Dialog } from 'vant'
import { getOrderList } from '@/API/getorderlist'
import { submitOrder } from '@/API/submitorder'
Vue.use(Cell)
Vue.use(CellGroup)
Vue.use(Card)
Vue.use(VanImage)
Vue.use(Switch)
Vue.use(ActionSheet)
Vue.use(Icon)
Vue.use(SubmitBar)
Vue.use(Popup)
Vue.use(AddressList)
Vue.use(Notify)
Vue.use(Toast)
Vue.use(Button)
Vue.use(Dialog)
export default {
  name: 'orderConfirm',
  data () {
    return {
      chosenAddressId: 0,
      index: 1,
      show: false,
      shows: false,
      items: [],
      res: [],
      Coupons: [],
      coupon: [],
      actions: [],
      Address: [],
      showAddress: false,
      PickedUpAddress: [],
      AllAddress: [],
      EDITAddress: [],
      actionss: [],
      NowDate: new Date().getTime(),
      coponId: null,
      Coponindex: null,
      CoponPrice: 0,
      payId: 0,
      payName: '余额',
      data: {}
    }
  },
  created () {
    getOrderList().then(res => {
      console.log(res)
      this.res = res.body
      // 自提地址的ID
      this.PickedUpAddress = res.body.shopAddress
      this.Coupons = res.body.Coupon
      console.log('优惠券', this.Coupons)
      this.items = res.body.Cart
      // console.log('商品列表', this.items)
      this.actionss = res.body.pay
      console.log('支付方式', this.actionss)
      this.AllAddress = res.body.myAddress

      this.EDITAddress = res.body.myAddress

      this.EDITAddress = this.EDITAddress.map(item => {
        item.tel = item.phone
        item.isDefault = item.is_default
        item.address = item.area + item.detail
        return item
      })
      this.Address = res.body.myAddress.filter(item => {
        return item.is_default !== false
      })
      if (this.Address.length === 0) {
        console.log('找不到默认地址')
        this.Address = res.body.myAddress
      }

      console.log('找到外卖的地址：', this.Address, this.Address[0].id)
      this.chosenAddressId = this.Address[0].id

      console.log('外卖ID', this.chosenAddressId, '自提ID：', this.PickedUpAddress.id)
    }).catch(e => console.log(e))
  },
  computed: {
    calcMoney () {
      return this.items.reduce((prev, curr) => {
        prev += curr.shop_price * curr.amount
        return prev
      }, 0)
    },
    calcTimer () {
      const time = new Date(this.NowDate + (1000 * 60 * (this.index === 1 ? 15 : 30)))
      if (time.getMinutes().length < 2) {
        return time.getHours() + ':0' + time.getMinutes()
      } else {
        return time.getHours() + ':' + time.getMinutes()
      }
    },
    calcTotalMoney () {
      const money = this.calcMoney
      if (money < this.CoponPrice) {
        return 0
      }
      return (money - this.CoponPrice) * 100
    }
  },
  methods: {
    gotoAddArress () {
      this.$router.push('/address')
    },
    changeCoponType () {
      if (this.Coupons.length) {
        this.show = true
      } else {
        Notify({ type: 'primary', message: '您没有优惠券哟！' })
      }
    },
    Toggle (index) {
      this.index = index
      if (index === 1) {
        console.log('自提模式')
        console.log(index)
      } else {
        console.log('外卖模式')
        console.log(index)
        console.log('默认地址ID：', this.chosenAddressId)
      }
    },
    changeAddressType () {
      this.showAddress = true
    },
    ChangeAddressIndex (a, b) {
      this.Address = [a]
      this.showAddress = false
      this.chosenAddressId = a.id
      console.log('选中了', a, '索引' + b, '地址id:' + this.chosenAddressId)
    },
    CoponType (id, index) {
      console.log(id)
      this.coponId = id
      this.Coponindex = index
      this.show = false
      this.CoponPrice = this.Coupons[index].sale_num
    },
    PayType (a, b) {
      // console.log(a, b)
      this.payId = a.id
      this.payName = a.name
      console.log(a.id, a.name)
    },
    SubmitOrder () {
      var addressID = 0
      if (this.index === 1) {
        addressID = this.PickedUpAddress.id
        console.log('自提模式:', '地址ID：', addressID, '优惠券ID：', this.coponId, '支付方式：', this.payId)
      } else {
        addressID = this.chosenAddressId
        console.log('自提模式:', '地址ID：', addressID, '优惠券ID：', this.coponId, '支付方式：', this.payId)
      }
      console.log(addressID)
      if (addressID === 0) {
        console.log('没有添加外送地址')
        Dialog.confirm({
          title: '友情提示',
          message: '您未添加默认地址，请前往地址管理处添加收货地址！点击下面确定，去添加地址'
        })
          .then(() => {
            this.$router.push('/address')
          })
          .catch(() => {
            // on cancel
          })
      } else {
        this.data = {
          coupon_id: this.coponId,
          address_id: addressID,
          payment: this.payId,
          isDelivery: this.index !== 1
        }
        submitOrder(this.data).then(res => {
          console.log(res.meta.msg)
          if (res.meta.code === 200) {
            Toast('提交订单成功！')
            setTimeout(() => {
              this.$router.push('/order')
            }, 1000)
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
[v-cloak]{
    display: none;
}
.order-confirm{
  overflow-x: hidden;
.top-box{
    display: flex;
    padding: 0 30px;
    justify-content: space-around;
    align-items: center;
  .btn_switch{
    width: 100px;
    height: 25px;
    border-radius: 20px;
    display: flex;
    text-align: center;
    line-height: 25px;
    border: 1px solid #7AA7D4;
    color: #7AA7D4;
      .btn-left{
      width: 50px;
      height: 25px;
      border-radius: 20px;
      }
      .btn-right{
        width: 50px;
        height: 25px;
        border-radius: 20px;
      }
    }
  .TimeOfArrival{
      font-size: 12px;
      text-align: center;
    }
  }
  .active{
    background: #7AA7D4;
    color:#fff;
  }
  .active1{
    background-color: #8AB2D9;
    color:#fff
  }
  .content{
    padding: 20px 40px;
    .evey{
      overflow: hidden;
    .qianbao{
        height:64px;
        display:flex;
        padding: 1px 0;
        overflow: hidden;
        align-items: center;
        margin:10px 0px;
        position: relative;
        text-align: center;
        line-height: 64px;
        .zuo{
          // flex:1;
          width: 20%;
          height:100%;
          display: block;
          border-top: 1px solid #8AB2D9;
          border-left: 1px solid #8AB2D9;
          border-bottom: 1px solid #8AB2D9;
        }
        .zhong{
          width: 10%;
          height:100%;
          display: block;
          position: relative;
          &::after{
            content: '';
            display: block;
            width: 100%;
            height:30px;
            position: absolute;
            top: -20px;
            left: 0;
            background: #fff;
            border: 1px solid #8AB2D9;
            border-radius: 50%;
          }
          &::before{
            content: '';
            display: block;
            width: 100%;
            height:30px;
            position: absolute;
            bottom: -20px;
            left: 0;
            background: #fff;
            border: 1px solid #8AB2D9;
            border-radius: 50%;
          }
        }
        .you{
          width: 70%;
          height:100%;
          border-top: 1px solid #8AB2D9;
          border-right: 1px solid #8AB2D9;
          border-bottom: 1px solid #8AB2D9;
        }
      }}
  }
  .weizhi{
    width: 100%;
  }
}

</style>
